﻿using App.Model;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace App.UI
{
    internal class Tree : TreeView
    {
        private TreeNode rootNode;
        private HashSet<TreeNode> processedNodes = new HashSet<TreeNode>();

        public event EventHandler<TreeNodeEvent> NodeStateChanged;

        public class TreeNodeEvent
        {
            public string Label { set; get; }
            public bool State { set; get; }

            public TreeNodeEvent(string label, bool state)
            {
                this.Label = label;
                this.State = state;
            }
        }

        public Tree()
        {
            Dock = DockStyle.Fill;
            this.AfterSelect += HandleAfterSelect;
        }

        public void setModel(TreeModel model)
        {
            rootNode = new TreeNode($"{model.Year}年");
            for (int i = 0; i < model.Month.Length; i++)
            {
                TreeNode monthNode = new TreeNode($"{model.Month[i]}月");

                foreach (int leafValue in model.Leaf[i])
                {
                    TreeNode dayNode = new TreeNode($"{leafValue}号炉");
                    monthNode.Nodes.Add(dayNode);
                }

                rootNode.Nodes.Add(monthNode);
            }

            this.Nodes.Add(rootNode);
            this.ExpandAll();
        }

        private void HandleAfterSelect(object sender, TreeViewEventArgs e)
        {
            if (rootNode != null && e.Node.Nodes.Count == 0)
            {
                HandleTreeNodeSelection(e.Node);
            }
        }

        private void HandleTreeNodeSelection(TreeNode node)
        {
            bool state = false;
            if (processedNodes.Contains(node))
            {
                processedNodes.Remove(node);
                state = true;
            }
            else
            {
                processedNodes.Add(node);
            }
            NodeStateChanged?.Invoke(this, new TreeNodeEvent(node.Text, state));
        }
    }
}
